package com.hualan.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EntityFactory<T> {
    private Class<T> obj;
    private Object obj1;
    public EntityFactory(Class<T> obj) throws Exception{
        this.obj = obj;
        this.obj1=this.obj.newInstance();
    }
    public T startCombine(ResultSet resultSet) throws Exception{
        Field[] fields=this.obj.getDeclaredFields();
        List<String> names=this.dealName(fields);
        Integer index=0;
        for(Field field:fields){
            this.setFieldValue(field, names.get(index++),resultSet);
        }
        return (T) this.obj1;
    }
    public List<String> dealName(Field[] fields){
        List<String> names=new ArrayList<>();
        for(Field field:fields){
            String m_name=field.getName();
            m_name=m_name.substring(0,1).toUpperCase()+m_name.substring(1);
            names.add("set"+m_name);
        }
        return names;
    }
    public void setFieldValue(Field field,String methodName,ResultSet resultSet) throws Exception{
        String type=field.getType().getSimpleName();
        if(type.equals("Integer")){
            Integer data=resultSet.getInt(field.getName());
            Method method=this.obj.getMethod(methodName,Integer.class);
            method.invoke(this.obj1,data);
        }else if(type.equals("String")){
            String data=resultSet.getString(field.getName());
            Method method=this.obj.getMethod(methodName,String.class);
            method.invoke(this.obj1,data);
        }else if(type.equals("Date")){
            Date data=resultSet.getDate(field.getName());
            Method method=this.obj.getMethod(methodName,Date.class);
            method.invoke(this.obj1,data);
        }else {
            EntityFactory entityFactory=new EntityFactory(field.getType());
            Object data=entityFactory.startCombine(resultSet);
            Method method=this.obj.getMethod(methodName,field.getType());
            method.invoke(this.obj1,data);
        }
    }
}
